using Catalog.Api.Data;  
using Catalog.Api.Models;  
using MongoDB.Driver;  
  
namespace Catalog.Api.HostedServices;  
  
public sealed class CatalogDataSeeder(IServiceProvider serviceProvider, ILogger<CatalogDataSeeder> logger) : IHostedService  
{  
    public async Task StartAsync(CancellationToken cancellationToken)  
    {  
        using var scope = serviceProvider.CreateScope();  
        var context = scope.ServiceProvider.GetRequiredService<CatalogDbContext>();  
        var count = await context.CatalogItems.CountDocumentsAsync(Builders<CatalogItem>.Filter.Empty, cancellationToken: cancellationToken);  
        if (count > 0)  
        {  
            logger.LogInformation("Catalog already contains data.");  
            return;  
        }  
        var seedItems = new[]  
        {  
            new CatalogItem  
            {  
                Name = "Adventure Backpack",  
                Description = "Durable backpack with 35L capacity and waterproof exterior.",  
                Price = 79.99m,  
                Stock = 42,  
                Category = "Outdoor",  
                PictureUrl = "https://placehold.co/600x400?text=Backpack",  
                CreatedAt = DateTime.UtcNow  
            },  
            new CatalogItem  
            {  
                Name = "Wireless Earbuds",  
                Description = "Noise-cancelling earbuds with 24h battery life and wireless charging.",  
                Price = 129.50m,  
                Stock = 120,  
                Category = "Electronics",  
                PictureUrl = "https://placehold.co/600x400?text=Earbuds",  
                CreatedAt = DateTime.UtcNow  
            },  
            new CatalogItem  
            {  
                Name = "Ceramic Coffee Mug",  
                Description = "Handmade matte ceramic mug, 350ml capacity.",  
                Price = 18.75m,  
                Stock = 300,  
                Category = "Home",  
                PictureUrl = "https://placehold.co/600x400?text=Mug",  
                CreatedAt = DateTime.UtcNow  
            }  
        };  
        await context.CatalogItems.InsertManyAsync(seedItems, cancellationToken: cancellationToken);  
        logger.LogInformation("Seeded {Count} catalog items", seedItems.Length);  
    }  
  
    public Task StopAsync(CancellationToken cancellationToken) => Task.CompletedTask;  
}
